<?php

namespace xing\contentSafe;

use xing\contentSafe\core\BaseSafe;
use xing\contentSafe\core\ImageSafeInterFace;
use xing\helper\resource\HttpHelper;

class TouTiao extends BaseSafe implements ImageSafeInterFace
{

    private $domain = 'https://developer.toutiao.com/';

    public $cacheType;
    public $appId;
    public $secret;
    public $targets = ['porn', 'disgusting', 'politics'];

    public static function init($appId, $secret)
    {
        $class = new static;
        $class->appId = $appId;
        $class->secret = $secret;
        return $class;
    }

    public function getAccessToken($reCache = false)
    {
        $cacheKey = 'TouTiaoAccessToken';

        $accessToken = $this->getCache($cacheKey);
        if (!empty($accessToken)) return $accessToken;

        $params = ['appid' => $this->appId, 'secret' => $this->secret, 'grant_type' => 'client_credential'];
        $result = HttpHelper::post($this->domain . 'api/apps/v2/token', json_encode($params),  ['Content-Type: application/json']);
        $data = json_decode($result)->data;
        if (empty($data->access_token ?? null)) throw new \Exception('请求accessToken失败, 返回值:' . $result);
        $this->setCache($cacheKey, $data->access_token, $data->expires_in - 1000);
        return $data->access_token;
    }

    public function getCacheDrive()
    {
        return \Yii::$app->cache;
        /*if ($this->cache == 'Yii') {
        } else {
            return $this->cache;
        }*/
    }

    public function getCache($cacheKey)
    {

        switch ($this->cacheType) {
            default:
                return $this->getCacheDrive()->get($cacheKey);

        }
    }

    public function setCache($cacheKey, $value, $time = null)
    {
        switch ($this->cacheType) {
            default:
                return $this->getCacheDrive()->set($cacheKey, $value, $time);

        }
    }

    /**
     * 检查图片是否为合法的
     * @param $urls
     * @return bool
     * @throws \Exception
     */
    public function getImageInfo(array $urls, $taskIds = '')
    {
        $return = [];
        $token = $this->getAccessToken();
        foreach ($urls as $url) {
            $post = [
                'app_id' => $this->appId,
                'access_token' => $token,
                'image' => $url
            ];
            $result = HttpHelper::post($this->domain . 'api/apps/censor/image', json_encode($post), ['Content-Type: application/json']);
            $result = json_decode($result, 1);
            if (!empty($result['error'] != '0')) {
                switch ($result['error']) {
                    case 2:
                        $this->getAccessToken(true);
                        return $this->getImageInfo($urls, $taskIds);
                        break;
                }
                throw new \Exception('内容安全请求失败：' . json_encode($result));
            }
            foreach ($result['predicts'] as $v) {
                $return[$v['model_name']][] = !$v['hit'] ?  BaseSafe::CHECK_OK : BaseSafe::CHECK_SERIOUS;
            }

        }
        return $return;
    }
    public function getTextInfo(array $contents, $taskIds = '')
    {
        return true;
    }
}
